package com.yuven.appframework.manager

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import com.yuven.appframework.manager.listener.IScreenListener
import java.lang.ref.WeakReference
import java.util.*

class ScreenOnOffManager {
    private lateinit var mContext:Context
    private lateinit var mScreenReceiver:SreenBroadcastReceiver
    private val mListeners: ArrayList<WeakReference<IScreenListener>> = ArrayList()
    companion object{
        @Volatile
        private var instance:ScreenOnOffManager?=null;

        fun getInstance():ScreenOnOffManager{
            if(instance == null){
                synchronized(ScreenOnOffManager::class){
                    if(instance == null)
                        instance = ScreenOnOffManager();
                }
            }
            return instance!!;
        }
    }

    fun init(context : Context){
        mContext = context
        mScreenReceiver = SreenBroadcastReceiver()
        val intentFilter = IntentFilter()
        intentFilter.addAction(Intent.ACTION_SCREEN_ON)
        intentFilter.addAction(Intent.ACTION_SCREEN_OFF)
        mContext.registerReceiver(mScreenReceiver,intentFilter)
    }

    private fun onScreenOn(){
        synchronized(mListeners){
            for(i in 0 until mListeners.size) {
                val listenerWeak = mListeners[i]
                listenerWeak.get()?.onScreenOn()
            }
        }
    }

    private fun onScreenOff(){
        synchronized(mListeners){
            for(i in 0 until mListeners.size) {
                val listenerWeak = mListeners[i]
                listenerWeak.get()?.onScreenOff()
            }
        }
    }

    fun registerListener(listener:IScreenListener){
        synchronized(mListeners){
            val listenerWef = WeakReference<IScreenListener>(listener)
            mListeners.add(listenerWef)
        }
    }

    fun unRegisterListener(listener:IScreenListener){
        synchronized(mListeners){
            for(i in 0..mListeners.size){
                val tempListener = mListeners[i]
                if(tempListener.get() === listener){
                    mListeners.removeAt(i)
                    break;
                }
            }
        }
    }


    inner class SreenBroadcastReceiver: BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            val action = intent!!.action
            if(Intent.ACTION_SCREEN_ON == action){
                onScreenOn();
            }else if(Intent.ACTION_SCREEN_OFF == action){
                onScreenOff();
            }
        }

    }
}